using System;
using System.Text;
using System.Collections;
using System.Collections.ObjectModel;

namespace PersistenceObject.Framework.Expressions
{
    public class InExpression : Expression
    {
        public InExpression()
        {
            this.isNotIn = false;
        }

        public InExpression(string name, IList values)
        {
            this.isNotIn = false;
            this.Name = name;
            this.Value = values;
        }

        public override string GetFilter(IDbDriver dbOperator)
        {
            IList list = (IList)this.Value;
            StringBuilder sb = new StringBuilder();
            sb.Append(this.Name);
            if (this.IsNotIn)
            {
                sb.Append(" not ");
            }
            sb.Append(" in (");
            for (int i = 0; i < list.Count; i++)
            {
                string paramName = string.Format("{0}{1}", this.Name, this.GetParamCount());
                if (i > 0)
                {
                    sb.Append(",");
                }
                if (paramName.LastIndexOf(".") != -1)
                {
                    paramName = paramName.Substring(paramName.LastIndexOf(".") + 1);
                }
                sb.Append(dbOperator.GetParameterName(paramName));
                this.param.Add(new FieldValue(paramName, list[i]));
            }
            sb.Append(")");
            return sb.ToString();
        }

        public override Collection<FieldValue> GetDataParams(IDbDriver dbOperator)
        {
            return this.param;
        }

        private bool isNotIn;
        public bool IsNotIn
        {
            get
            {
                return this.isNotIn;
            }
            set
            {
                this.isNotIn = value;
            }
        }

        #region Only for SqlServer2005 ServiceBroker
        public override string ServiceBrokerGetFilter(IDbDriver dbOperator)
        {
            IList list = (IList)this.Value;
            StringBuilder sb = new StringBuilder();
            sb.Append(this.Name);
            if (this.IsNotIn)
            {
                sb.Append(" not ");
            }
            sb.Append(" in (");
            for (int i = 0; i < list.Count; i++)
            {
                if (i > 0)
                {
                    sb.Append(",");
                }
                sb.Append(ServiceBroker.Utility.Instance.GetParamValue(list[i]));
            }
            sb.Append(")");
            return sb.ToString();
        }
        #endregion

    }
}